package com.gxa.servlet;

import com.alibaba.fastjson.JSON;
import com.gxa.entity.User;
import com.gxa.service.UserService;
import com.gxa.service.impl.UserServiceImpl;
import com.gxa.utils.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();

        //接收参数
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        System.out.println(username);
        System.out.println(pwd);

        UserService userService = new UserServiceImpl();
        User user = userService.getByUsernameAndPwd(username, pwd);
        System.out.println(user);

        if(user != null){
            session.setAttribute("user",user);

            Result result = new Result(0,"success",null);
            String userJsonStr = JSON.toJSONString(result);
            out.print(userJsonStr);
        }else {
            Result result = new Result(1,"用户名或者密码错误",null);
            String userJsonStr = JSON.toJSONString(result);
            out.print(userJsonStr);
        }
    }
}
